package com.mikufufu.blog.utils;

import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class RsaUtils {

    // 密钥算法类型
    private static final String ALGORITHM = "RSA";
    // 加密填充方式
    private static final String TRANSFORMATION = "RSA/ECB/PKCS1Padding";
    // 密钥长度（推荐2048位）
    private static final int KEY_SIZE = 2048;

    /**
     * 生成RSA密钥对
     * @return 包含Base64编码公钥私钥的Map
     */
    public static KeyPair generateKeyPair() throws NoSuchAlgorithmException {
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(ALGORITHM);
        keyPairGen.initialize(KEY_SIZE, new SecureRandom());
        return keyPairGen.generateKeyPair();
    }

    /**
     * 公钥加密
     * @param plainText 明文
     * @param publicKey Base64编码的公钥字符串
     * @return Base64编码的密文
     */
    public static String encrypt(String plainText, String publicKey) throws Exception {
        byte[] keyBytes = java.util.Base64.getDecoder().decode(publicKey);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        PublicKey pubKey = KeyFactory.getInstance(ALGORITHM).generatePublic(keySpec);

        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        return java.util.Base64.getEncoder().encodeToString(cipher.doFinal(plainText.getBytes()));
    }

    /**
     * 私钥解密
     * @param cipherText Base64编码的密文
     * @param privateKey Base64编码的私钥字符串
     * @return 解密后的明文
     */
    public static String decrypt(String cipherText, String privateKey) throws Exception {
        byte[] keyBytes = java.util.Base64.getDecoder().decode(privateKey);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        PrivateKey priKey = KeyFactory.getInstance(ALGORITHM).generatePrivate(keySpec);

        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        cipher.init(Cipher.DECRYPT_MODE, priKey);
        byte[] decrypted = cipher.doFinal(java.util.Base64.getDecoder().decode(cipherText));
        return new String(decrypted, StandardCharsets.UTF_8);
    }

    /**
     * 获取Base64编码的公钥字符串
     */
    public static String getPublicKeyString(KeyPair keyPair) {
        return java.util.Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded());
    }

    /**
     * 获取Base64编码的私钥字符串
     */
    public static String getPrivateKeyString(KeyPair keyPair) {
        return Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded());
    }

}
